% appendixb.tex
% This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 New Zealand License.
% To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/nz
% or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.


\chapter{Built-in Functions}\label{app:builtinfunctions}

Python has a number of built-in functions---functions that can be used without needing to \textbf{import} them first.  Some of the available built-in functions are listed below.

\subsection*{abs}\index{functions!abs}

The \textbf{abs} function returns the absolute value of a number.  An absolute value is a number that is not negative.  So the absolute value of 10 is 10, and the absolute value of -20.5 is 20.5.  For example:

\begin{listing}
\begin{verbatim}
>>> print(abs(10))
10
>>> print(abs(-20.5))
20.5
\end{verbatim}
\end{listing}

\subsection*{bool}\index{functions!bool}

The \textbf{bool} function returns either True or False based on the value passed as its parameter. For numbers, 0 returns False, while any other number returns True:

\begin{listing}
\begin{verbatim}
>>> print(bool(0))
False
>>> print(bool(1))
True
>>> print(bool(1123.23))
True
>>> print(bool(-500))
True
\end{verbatim}
\end{listing}

For other values, None returns False while anything else returns True:

\begin{listing}
\begin{verbatim}
>>> print(bool(None))
False
>>> print(bool('a'))
True 
\end{verbatim}
\end{listing}

\subsection*{cmp}\index{functions!cmp}

The \textbf{cmp} function compares two values and returns a negative number if the first value is less than the second; returns 0 if the first value is equal to the second; and returns a positive number if the first value is greater than the second. For example, 1 is less than 2:

\begin{listing}
\begin{verbatim}
>>> print(cmp(1,2))
-1
\end{verbatim}
\end{listing}

\noindent
And 2 is equal to 2:

\begin{listing}
\begin{verbatim}
>>> print(cmp(2,2))
0
\end{verbatim}
\end{listing}

\noindent
But 2 is greater than 1:

\begin{listing}
\begin{verbatim}
>>> print(cmp(2,1))
1
\end{verbatim}
\end{listing}

\noindent
Compare doesn't only work with numbers. You can use other values, such as strings:

\begin{listing}
\begin{verbatim}
>>> print(cmp('a','b'))
-1
>>> print(cmp('a','a'))
0
>>> print(cmp('b','a'))
1
\end{verbatim}
\end{listing}

\noindent
But do be careful with strings; the return value may not be exactly what you expect$\ldots$

\begin{listing}
\begin{verbatim}
>>> print(cmp('a','A'))
1
>>> print(cmp('A','a'))
-1
\end{verbatim}
\end{listing}

A lower-case 'a' is actually greater than an upper-case 'A'. Of course$\ldots$

\begin{listing}
\begin{verbatim}
>>> print(cmp('aaa','aaaa'))
-1
>>> print(cmp('aaaa','aaa'))
1
\end{verbatim}
\end{listing}

\noindent
$\ldots$3 letter a's (aaa) are less than 4 letter a's (aaaa).

\subsection*{dir}\index{functions!dir}

The \textbf{dir} function returns a list of information about a value.  You can use dir on strings, numbers, functions, modules, objects, classes---pretty much anything.  On some values, the information might not be all that useful (in fact it might not make a huge amount of sense at all).  For example, calling dir on the number 1 results in$\ldots$

\begin{listingignore}
\begin{verbatim}
>>> dir(1)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', 
'__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', 
'__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', 
'__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', 
'__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', 
'__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', 
'__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__',
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__',
'__xor__']
\end{verbatim}
\end{listingignore}

$\ldots$quite a large number of special functions. Whereas calling dir on the string 'a' results in...

\begin{listingignore}
\begin{verbatim}
>>> dir('a')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', 
'__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__',
'__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', 
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 
'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 
'swapcase', 'title', 'translate', 'upper', 'zfill']
\end{verbatim}
\end{listingignore}

Which shows you there are functions such as \code{capitalize} (change the first letter in a string to a capital)$\ldots$

\begin{listing}
\begin{verbatim}
>>> print('aaaaa'.capitalize())
Aaaaa
\end{verbatim}
\end{listing}

$\ldots$\code{isalnum} (which returns True if a string is alphanumeric---contains only letters and numbers), \code{isalpha} (which returns True if a string contains only letters), and so on. Dir can be useful when you have a variable and quickly want to find out what you can do with it.

\subsection*{eval}\index{functions!eval}

The \textbf{eval} function takes a string as a parameter and runs it as though it were a Python expression.  This is similar to the \textbf{exec} keyword, but works a little differently.  With exec you can create mini Python programs in your string, but eval only allows simple expressions, such as:

\begin{listing}
\begin{verbatim}
>>> eval('10*5')
50
\end{verbatim}
\end{listing}

\subsection*{file}\index{functions!file}

A function to open a file and return a file object with functions that can access information in the file (the contents of the file, its size and so on). You can find more information about file and file objects in Chapter~\ref{ch:ashortchapteraboutfiles}.

\subsection*{float}\index{functions!float}

The \textbf{float} function converts a string or a number into a floating point number. A floating point number is a number with a decimal place (also called a real number). For example, the number 10 is an `integer' (also called a whole number), but 10.0, 10.1, 10.253, and so on, are all `floats'. You can convert a string to a float by calling:

\begin{listing}
\begin{verbatim}
>>> float('12')
12.0
\end{verbatim}
\end{listing}

\noindent
You can use a decimal place in the string as well:

\begin{listing}
\begin{verbatim}
>>> float('123.456789')
123.456789
\end{verbatim}
\end{listing}

\noindent
A number can be converted to a float by calling:

\begin{listing}
\begin{verbatim}
>>> float(200)
200.0
\end{verbatim}
\end{listing}

\noindent
Of course, converting a floating point number just returns another floating point number:

\begin{listing}
\begin{verbatim}
>>> float(100.123)
100.123
\end{verbatim}
\end{listing}

\noindent
Calling float with no arguments, returns 0.0.

\subsection*{int}\index{functions!int}

The \textbf{int} function converts a string or a number into a whole number (or integer). For example:

\begin{listing}
\begin{verbatim}
>>> int(123.456)
123
>>> int('123')
123
\end{verbatim}
\end{listing}

This function works a little differently from the \textbf{float} function. If you try to convert a floating point number in a string, you will get an error message:

\begin{listing}
\begin{verbatim}
>>> int('123.456')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123.456'
\end{verbatim}
\end{listing}

\noindent
However, if you call int with no argument, then 0 is returned.

\subsection*{len}\index{functions!len}

The \textbf{len} function returns the length of an object. In this case of a string, it returns the number of characters in the string:

\begin{listing}
\begin{verbatim}
>>> len('this is a test string')
21
\end{verbatim}
\end{listing}

\noindent
For a list or a tuple, it returns the number of items:

\begin{listing}
\begin{verbatim}
>>> mylist = [ 'a', 'b', 'c', 'd' ]
>>> print(len(mylist))
4
>>> mytuple = (1,2,3,4,5,6)
>>> print(len(mytuple))
6
\end{verbatim}
\end{listing}

\noindent
For a map, it also returns the number of items:

\begin{listing}
\begin{verbatim}
>>> mymap = { 'a' : 100, 'b' : 200, 'c' : 300 }
>>> print(len(mymap))
3
\end{verbatim}
\end{listing}

\noindent
You might find the len function useful with loops, if you want to count through the elements in a list.  You could do this using the following code:

\begin{listing}
\begin{verbatim}
>>> mylist = [ 'a', 'b', 'c', 'd' ]
>>> for item in mylist:
...     print(item)
\end{verbatim}
\end{listing}

\noindent
Which would print out all the items in the list (a,b,c,d)---but what if you wanted to print the index position of each item in the list?  In this case we could find the length of the list, then count through the items as follows:

\begin{listing}
\begin{verbatim}
>>> mylist = [ 'a', 'b', 'c', 'd' ]
>>> length = len(mylist)
>>> for x in range(0, length):
...     print('the item at index %s is %s' % (x, mylist[x]))
... 
the item at index 0 is a
the item at index 1 is b
the item at index 2 is c
the item at index 3 is d
\end{verbatim}
\end{listing}

\noindent
We store the length of the list in the variable `length', and then use that variable in the \code{range} function to create our loop.

\subsection*{max}\index{functions!max}

The \textbf{max} function returns the largest item in a list, tuple or even a string. For example:

\begin{listing}
\begin{verbatim}
>>> mylist = [ 5, 4, 10, 30, 22 ]
>>> print(max(mylist))
30
\end{verbatim}
\end{listing}

\noindent
A string with the items are separated by commas or spaces will also work:

\begin{listing}
\begin{verbatim}
>>> s = 'a,b,d,h,g'
>>> print(max(s))
h
\end{verbatim}
\end{listing}

\noindent
And you don't have to use lists, or tuples or strings. You can also call the max function directly with a number of arguments:

\begin{listing}
\begin{verbatim}
>>> print(max(10, 300, 450, 50, 90))
450
\end{verbatim}
\end{listing}

\subsection*{min}\index{functions!min}

The \textbf{min} function works in the same way as max, except it returns the smallest item in the list/tuple/string:

\begin{listing}
\begin{verbatim}
>>> mylist = [ 5, 4, 10, 30, 22 ]
>>> print(min(mylist))
4
\end{verbatim}
\end{listing}

\subsection*{range}\index{functions!range}

The \textbf{range} function is mainly used in for-loops, when you want to loop through some code a number of times. We first saw range in Chapter~\ref{ch:againandagain}, so we've seen how to use it with two arguments, but it can also be used with three arguments. Here's another example of range with two arguments:

\begin{listing}
\begin{verbatim}
>>> for x in range(0, 5):
...     print(x)
... 
0
1
2
3
4
\end{verbatim}
\end{listing}

\noindent
What you might not have realised, is that the \code{range} function actually just returns a special object (called an iterator) which the for-loop then works through. You can convert the iterator into a list (oddly enough, using the function \code{list}), so if you print the return value when calling range, you'll see the numbers it contains:

\begin{listing}
\begin{verbatim}
>>> print(list(range(0, 5)))
[0, 1, 2, 3, 4]
\end{verbatim}
\end{listing}

\noindent
You get a list of numbers that can be assigned to variables and used elsewhere in your program:

\begin{listingignore}
\begin{verbatim}
>>> my_list_of_numbers = list(range(0, 30))
>>> print(my_list_of_numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
\end{verbatim}
\end{listingignore}

\noindent
Range also takes a third argument, called a `step' (the first two arguments are called the `start' and the `stop'). If the step value is not passed into the function (in other words, when you call it with only the start and stop values), by default the number 1 is used. But what happens when we pass the number 2 as the step?  You can see the result in the following example:

\begin{listing}
\begin{verbatim}
>>> my_list_of_numbers = list(range(0, 30, 2))
>>> print(my_list_of_numbers)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
\end{verbatim}
\end{listing}

\noindent
Each number in the list increases by 2 from the previous number. We can use larger steps:

\begin{listing}
\begin{verbatim}
>>> mylist = list(range(0, 500, 50))
>>> print(mylist)
[0, 50, 100, 150, 200, 250, 300, 350, 400, 450]
\end{verbatim}
\end{listing}

This creates a list from 0 to 500 (but not including 500, of course), incrementing the numbers by 50.

\subsection*{sum}\index{functions!sum}

The \textbf{sum} function adds up items in a list and returns the total number. For example:

\begin{listing}
\begin{verbatim}
>>> mylist = list(range(0, 500, 50))
>>> print(mylist)
[0, 50, 100, 150, 200, 250, 300, 350, 400, 450]

>>> print(sum(mylist))
2250
\end{verbatim}
\end{listing}

\newpage